package com.leaves.contoller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import com.leaves.entity.AuthInfo;
import com.leaves.entity.RoleInfo;
import com.leaves.entity.vo.AuthInfoVo;
import com.leaves.entity.vo.RoleInfoVo;
import com.leaves.response.ApiResult;
import com.leaves.service.AuthInfoService;
import com.leaves.service.RoleInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2022年06月06日  13时48分40秒
 * @Description:
 */
@RestController
@RequestMapping("/v1/role-auth")
public class RoleAuthController {

    @Resource
    private RoleInfoService roleInfoService;
    @Resource
    private AuthInfoService authInfoService;


    /**
     * SaMode.AND, 标注一组权限，会话必须全部具有才可通过校验
     * SaMode.OR, 标注一组权限，会话只要具有其一即可通过校验
     * <p>
     * orRole 字段代表权限认证未通过时的次要选择，两者只要其一认证成功即可通过校验，其有三种写法：
     * 写法一：orRole = "admin"，代表需要拥有角色 admin 。
     * 写法二：orRole = {"admin", "manager", "staff"}，代表具有三个角色其一即可。
     * 写法三：orRole = {"admin, manager, staff"}，代表必须同时具有三个角色。
     *
     * @return
     */
    @SaCheckPermission(value = {"front-query"}, mode = SaMode.AND)
    @SaCheckRole(value = {"front", "back"}, mode = SaMode.OR)
    @SaCheckLogin
    @RequestMapping("/role/list")
    public ApiResult getRoleList() {
        List<RoleInfo> roleInfoList = roleInfoService.list();
        List<RoleInfoVo> list = new ArrayList<>();
        roleInfoList.forEach(roleInfo -> {
            RoleInfoVo roleInfoVo = new RoleInfoVo();
            BeanUtils.copyProperties(roleInfo, roleInfoVo);
            list.add(roleInfoVo);
        });
        return ApiResult.successData(list);
    }

    @RequestMapping("/auth/list")
    public ApiResult getAuthList() {
        List<AuthInfo> authInfoList = authInfoService.list();
        List<AuthInfoVo> list = new ArrayList<>();
        authInfoList.forEach(authInfo -> {
            AuthInfoVo authInfoVo = new AuthInfoVo();
            BeanUtils.copyProperties(authInfo, authInfoVo);
            list.add(authInfoVo);
        });
        return ApiResult.successData(list);
    }
}
